import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/index.js'
import Layout from '@/page/public/layout.vue'
//首页
import Dashboard from '@/page/Dashboard/index.vue'
//登录界面
import login from '@/page/login/index.vue'
import navigation from '@/page/system/navigation.vue'
import category from '@/page/system/category.vue'
//角色组管理
import users from '@/page/system/users'
import rules from '@/page/system/rules'

Vue.use(Router)

const router = new Router({
  //以 / 开头的嵌套路径会被当作根路径
  routes: [{
    //默认重定向至“我的面板”页面
    path: '/',
    redirect: { name: 'home' }
  }, {
    name: 'login',
    path: '/login',
    meta: { pagename: '用户登录' },
    component: login
  }, {
    name: 'register',
    path: '/register',
    meta: { pagename: '用户注册' },
    component: login
  }, {
    name: 'app',
    path: '/',
    meta: { pagename: '主页' },
    component: Layout,
    //子路由
    children: [{
        name: 'home',
        path: 'Dashboard',
        meta: { pagename: '我的面板' },
        component: Dashboard,
      },
      {
        name: 'navigation',
        path: 'navigation',
        meta: { pagename: '导航菜单管理' },
        component: navigation,
      },
      {
        name: 'category',
        path: 'category',
        meta: { pagename: '字典表管理' },
        component: category
      },
      {
        name: 'rules',
        path: 'rules',
        meta: { pagename: '角色组管理' },
        component: rules,
      },
      {
        name: 'users',
        path: 'users',
        meta: { pagename: '管理员管理' },
        component: users
      }
    ]
  }],

})
//检测token是否存在，否则退回登录
router.beforeEach((to, from, next) => {
  if (to.name === 'login' || to.name === 'register') {
    next();
    return
  } else {
    if (to.name !== 'login' && !store.state.userinfo.userinfo.token) {
      next('login')
    } else {
      next();
    }
  }
})

export default router
